package cn.edu.nju.bankaccount.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.edu.nju.bankaccount.dao.AccountDao;
import cn.edu.nju.bankaccount.dao.DaoHelper;
import cn.edu.nju.bankaccount.factory.DaoFactory;
import cn.edu.nju.bankaccount.model.Account;
import cn.edu.nju.bankaccount.model.User;

public class AccountDaoImpl implements AccountDao{
	private static AccountDaoImpl accountDao=new AccountDaoImpl();
	private static DaoHelper daoHelper=DaoHelperImpl.getBaseDaoInstance();

	public static AccountDao getInstance() {
		return accountDao;
	}
	public List findAll() {
		Connection con=daoHelper.getConnection();
		PreparedStatement stmt=null;
		ResultSet result=null;
		String sql = "select * from `account`";
		ArrayList<Account> list=new ArrayList<Account>();
		try 
		{
			stmt=con.prepareStatement(sql);
			result=stmt.executeQuery();
			while(result.next())
			{
				Account account = setAccount(result);
				list.add(account);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			daoHelper.closeAll(con, stmt, result);
		}
		return list;
	}
	public Account findById(String id) {
		Connection con= null;
		PreparedStatement stmt=null;
		ResultSet result=null;
		String sql = "select * from `account` where id=?";
		Account account = null;
		try 
		{
			con=daoHelper.getConnection();
			stmt=con.prepareStatement(sql);
			stmt.setString(1, id);
			result=stmt.executeQuery();
			
			while(result.next())
			{
				account = setAccount(result);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			daoHelper.closeAll(con, stmt, result);
		}
		return account;
	}
	
	public Account findByAccountNum(String accountNum) {
		Connection con= null;
		PreparedStatement stmt=null;
		ResultSet result=null;
		String sql = "select * from `account` where accountNum="+accountNum;
		System.out.println(sql);
		Account account = null;
		try 
		{
			con=daoHelper.getConnection();
			stmt=con.prepareStatement(sql);
			result=stmt.executeQuery();
			while(result.next())
			{
				account = setAccount(result);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			daoHelper.closeAll(con, stmt, result);
		}
		return account;
	}
	public void save(Account account) {
		
	}
	
	public Account setAccount(ResultSet result) throws SQLException{
		Account account = new Account();
		account.setAccountNum(result.getInt("accountNum"));
		int userId = result.getInt("userId");
		System.out.println("UserId="+userId);
		User user = DaoFactory.getUserDao().findById(userId+"");
		account.setUser(user);
		account.setMoney(result.getDouble("money"));
		return account;
	}
}
